import { PaginationProps } from "ant-design-vue";
import { computed, ref, UnwrapRef } from "vue";
import { PaginationParam, PaginationResult } from "/@/api/models";
import { ResponseData } from "/@/api/req";
const DEFAULT_PAGE_SIZE = 10;

export function usePagination<T, K>(
  reqApi: (params: PaginationParam<K>) => Promise<PaginationResult<T> | null | ResponseData<PaginationResult<T>>>,
  initPageSize?: number
) {
  const loading = ref(false);
  const current = ref(1);
  const total = ref(0);
  const pageSize = ref(initPageSize || DEFAULT_PAGE_SIZE);
  const pageData = ref<T[]>([]);

  // let sortOrder: OrderRule | "" = "";
  // let sortField: SortField | "" = "";
  let searchModel: any = {};

  async function refreshPagination(params?: PaginationParam<K>): Promise<boolean> {
    params = params || {};
    if (params.pageNum) {
      current.value = params.pageNum;
    }
    if (params.pageSize) {
      pageSize.value = params.pageSize;
    }
    if (params.model) {
      Object.assign(searchModel, params.model);
      for (const i in searchModel) {
        if (searchModel[i] === "" || searchModel[i] === null) {
          delete searchModel[i];
        }
      }
    } else if (params.model === null) {
      searchModel = {};
    }
    loading.value = true;
    const result = (await reqApi(
      Object.assign(
        {
          pageNum: current.value,
          pageSize: pageSize.value,
          // model: searchModel,
          // sort: sortField,
          // order: sortOrder,
        },
        searchModel
      )
    )) as PaginationResult<T>;
    if (result) {
      total.value = +result.total;
      pageData.value = result.list as UnwrapRef<T[]>;
    }
    loading.value = false;
    return !!result;
  }

  const pagination = computed<PaginationProps>(() => ({
    total: total.value,
    current: current.value,
    pageSize: pageSize.value,
    showSizeChanger: true,
    onChange: (pageNum, pageSize) => {
      refreshPagination({
        pageNum,
        pageSize,
      });
    },
    onShowSizeChange: (pageNum, pageSize) => {
      refreshPagination({
        pageNum,
        pageSize,
      });
    },
  }));

  return {
    refreshPagination,
    pagination,
    current,
    pageSize,
    pageData,
    total,
    loading,
  };
}
